import React, { Component } from 'react'
import { connect } from 'react-redux'
import PropTypes from 'prop-types';
import {
  NavBar,
  Icon,
  List,
  TextareaItem,
  Button
} from 'antd-mobile'

import './chat.scss'
import { sendMessage, modifyReadStatue } from '../../redux/actions'

const ListItem = List.Item


class Chat extends Component {

  static propTypes = {
    user: PropTypes.object.isRequired,
    chat: PropTypes.object.isRequired,
    sendMessage: PropTypes.func.isRequired,
    modifyReadStatue: PropTypes.func.isRequired
  }

  state = {
    content: ''
  }

  componentDidMount() {
    // 初始化聊天页面滚动到底部
    window.scrollTo(0, document.body.scrollHeight)
    // 修改未读为已读
    const from = this.props.match.params.userid
    const userId = this.props.user._id
    this.props.modifyReadStatue(from, userId)
  }

  componentDidUpdate() {
    // 发送消息更新后聊天页面滚动到底部
    window.scrollTo(0, document.body.scrollHeight)
  }

  send = ()=>{
    const from = this.props.user._id
    const to = this.props.match.params.userid
    const { content } = this.state
    if (content) {
      this.props.sendMessage({ from, to, content })
      this.setState({content : ''})
    }
  }

  render() {
    const {user} = this.props
    const {chatMsgs, users} = this.props.chat
    if (!users[user._id]) {
      // 只少有一个数据，即自己，没有数据不渲染，等待返回数据
      return null
    }

    // 根据id获取目标聊天对象的名称、头像
    const targetId = this.props.match.params.userid
    const targetHeader = users[targetId].header
    const targetName = users[targetId].username
    const targetHeaderImg = require(`../../assets/images/${targetHeader}.png`)
    // 获取自己的头像
    const myHeaderImg = require(`../../assets/images/${user.header}.png`)
    
    // 计算当前聊天的聊天id,用sort()排序保证与后代一致
    const chatId = [user._id, targetId].sort().join('_')
    // 根据聊天id筛选与当前聊天对象的聊天信息
    const messages = chatMsgs.filter((msg) => msg.chat_id === chatId)
    
    return (
      <div id='chat-page'>
        <NavBar
          className="chat-nav"
          icon={<Icon type="left" />}
          onLeftClick={() => this.props.history.goBack()}
        >{targetName}</NavBar>
        <List className="chat-list"> 
          {
            messages.map((msg) => {
              if (msg.from === user._id) {
                // 自己发出的消息
                return (
                  <ListItem className="chat-wrap" key={msg._id}>
                    <div className="chat-me">
                      <div className="message">{msg.content}</div>
                      <img className="header-img" src={myHeaderImg} alt=""/>
                    </div>
                  </ListItem>
                ) 
              } else {
                // 目标对象发送的消息
                return (
                  <ListItem className="chat-wrap" key={msg._id}>
                    <div className="chat-others">
                      <img className="header-img" src={targetHeaderImg} alt=""/>
                      <div className="message">{msg.content}</div>
                    </div>
                  </ListItem>
                )
              }
            })
          }
        </List>
        <div className='foot-bar'>
          <TextareaItem 
            autoHeight
            value={this.state.content} 
            onChange={(value) => {this.setState({content : value})}}
            placeholder="请输入"
          />
          <Button type="primary" onClick={this.send}>发送</Button>
        </div>
      </div>
    )
  }
}

export default connect(
  state => ({ user: state.user, chat: state.chat}),
  { sendMessage, modifyReadStatue }
)(Chat)
